using System;
using ch.ethz.ssh2.crypto;
using ch.ethz.ssh2.crypto.digest;
using ch.ethz.ssh2.log;
using ch.ethz.ssh2.packets;
using Org.BouncyCastle.Math;
namespace ch.ethz.ssh2.signature
{

    /// <summary> RSASHA1Verify.
    /// 
    /// </summary>
    /// <author>  Christian Plattner
    /// </author>
    /// <version>  2.50, 03/15/10
    /// </version>
    public class RSASHA1Verify
    {
        //UPGRADE_NOTE: Final was removed from the declaration of 'log '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
        //UPGRADE_NOTE: The initialization of  'log' was moved to static method 'ch.ethz.ssh2.signature.RSASHA1Verify'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'"
        private static readonly Logger log;

        public static RSAPublicKey decodeSSHRSAPublicKey(byte[] key)
        {
            TypesReader tr = new TypesReader(key);

            System.String key_format = tr.readString();

            if (key_format.Equals("ssh-rsa") == false)
                throw new System.ArgumentException("This is not a ssh-rsa public key");

            BigInteger e = tr.readMPINT();
            BigInteger n = tr.readMPINT();

            if (tr.remain() != 0)
                throw new System.IO.IOException("Padding in RSA public key!");

            return new RSAPublicKey(e, n);
        }

        public static byte[] encodeSSHRSAPublicKey(RSAPublicKey pk)
        {
            TypesWriter tw = new TypesWriter();

            tw.writeString("ssh-rsa");
            tw.writeMPInt(pk.E);
            tw.writeMPInt(pk.N);

            return tw.getBytes();
        }

        public static RSASignature decodeSSHRSASignature(byte[] sig)
        {
            TypesReader tr = new TypesReader(sig);

            System.String sig_format = tr.readString();

            if (sig_format.Equals("ssh-rsa") == false)
                throw new System.IO.IOException("Peer sent wrong signature format");

            /* S is NOT an MPINT. "The value for 'rsa_signature_blob' is encoded as a string
            * containing s (which is an integer, without lengths or padding, unsigned and in
            * network byte order)." See also below.
            */

            byte[] s = tr.readByteString();

            if (s.Length == 0)
                throw new System.IO.IOException("Error in RSA signature, S is empty.");

            if (log.Enabled)
            {
                log.log(80, "Decoding ssh-rsa signature string (length: " + s.Length + ")");
            }

            if (tr.remain() != 0)
                throw new System.IO.IOException("Padding in RSA signature!");

            //UPGRADE_ISSUE: Constructor 'java.math.BigInteger.BigInteger' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javamathBigIntegerBigInteger_int_byte[]'"
            return new RSASignature(new BigInteger(1, s));
        }

        public static byte[] encodeSSHRSASignature(RSASignature sig)
        {
            TypesWriter tw = new TypesWriter();

            tw.writeString("ssh-rsa");

            /* S is NOT an MPINT. "The value for 'rsa_signature_blob' is encoded as a string
            * containing s (which is an integer, without lengths or padding, unsigned and in
            * network byte order)."
            */

            //UPGRADE_ISSUE: Method 'java.math.BigInteger.toByteArray' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javamathBigIntegertoByteArray'"
            byte[] s = sig.S.ToByteArray();

            /* Remove first zero sign byte, if present */

            if ((s.Length > 1) && (s[0] == 0x00))
                tw.writeString(s, 1, s.Length - 1);
            else
                tw.writeString(s, 0, s.Length);

            return tw.getBytes();
        }

        public static RSASignature generateSignature(byte[] message, RSAPrivateKey pk)
        {
            SHA1 md = new SHA1();
            md.update(message);
            byte[] sha_message = new byte[md.DigestLength];
            md.digest(sha_message);

            byte[] der_header = new byte[] { (byte)(0x30), (byte)(0x21), (byte)(0x30), (byte)(0x09), (byte)(0x06), (byte)(0x05), (byte)(0x2b), (byte)(0x0e), (byte)(0x03), (byte)(0x02), (byte)(0x1a), (byte)(0x05), (byte)(0x00), (byte)(0x04), (byte)(0x14) };

            //UPGRADE_ISSUE: Method 'java.math.BigInteger.bitLength' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javamathBigIntegerbitLength'"
            int rsa_block_len = (pk.N.BitLength + 7) / 8;

            int num_pad = rsa_block_len - (2 + der_header.Length + sha_message.Length) - 1;

            if (num_pad < 8)
                throw new System.IO.IOException("Cannot sign with RSA, message too long");

            byte[] sig = new byte[der_header.Length + sha_message.Length + 2 + num_pad];

            sig[0] = (byte)(0x01);

            for (int i = 0; i < num_pad; i++)
            {
                sig[i + 1] = (byte)0xff;
            }

            sig[num_pad + 1] = (byte)(0x00);

            Array.Copy(der_header, 0, sig, 2 + num_pad, der_header.Length);
            Array.Copy(sha_message, 0, sig, 2 + num_pad + der_header.Length, sha_message.Length);

            BigInteger m = new BigInteger(1, sig);

            BigInteger s = m.ModPow(pk.D, pk.N);

            return new RSASignature(s);
        }

        public static bool verifySignature(byte[] message, RSASignature ds, RSAPublicKey dpk)
        {
            SHA1 md = new SHA1();
            md.update(message);
            byte[] sha_message = new byte[md.DigestLength];
            md.digest(sha_message);

            BigInteger n = dpk.N;
            BigInteger e = dpk.E;
            BigInteger s = ds.S;

            if (n.CompareTo((System.Object)s) <= 0)
            {
                log.log(20, "ssh-rsa signature: n.compareTo(s) <= 0");
                return false;
            }

            int rsa_block_len = (n.BitLength + 7) / 8;

            /* And now the show begins */

            if (rsa_block_len < 1)
            {
                log.log(20, "ssh-rsa signature: rsa_block_len < 1");
                return false;
            }

            byte[] v = s.ModPow(e, n).ToByteArray();

            int startpos = 0;

            if ((v.Length > 0) && (v[0] == 0x00))
                startpos++;

            if ((v.Length - startpos) != (rsa_block_len - 1))
            {
                log.log(20, "ssh-rsa signature: (v.length - startpos) != (rsa_block_len - 1)");
                return false;
            }

            if (v[startpos] != 0x01)
            {
                log.log(20, "ssh-rsa signature: v[startpos] != 0x01");
                return false;
            }

            int pos = startpos + 1;

            while (true)
            {
                if (pos >= v.Length)
                {
                    log.log(20, "ssh-rsa signature: pos >= v.length");
                    return false;
                }
                if (v[pos] == 0x00)
                    break;
                if (v[pos] != (byte)0xff)
                {
                    log.log(20, "ssh-rsa signature: v[pos] != (byte) 0xff");
                    return false;
                }
                pos++;
            }

            int num_pad = pos - (startpos + 1);

            if (num_pad < 8)
            {
                log.log(20, "ssh-rsa signature: num_pad < 8");
                return false;
            }

            pos++;

            if (pos >= v.Length)
            {
                log.log(20, "ssh-rsa signature: pos >= v.length");
                return false;
            }

            SimpleDERReader dr = new SimpleDERReader(v, pos, v.Length - pos);

            byte[] seq = dr.readSequenceAsByteArray();

            if (dr.available() != 0)
            {
                log.log(20, "ssh-rsa signature: dr.available() != 0");
                return false;
            }

            dr.resetInput(seq);

            /* Read digestAlgorithm */

            byte[] digestAlgorithm = dr.readSequenceAsByteArray();

            /* Inspired by RFC 3347, however, ignoring the comment regarding old BER based implementations */

            if ((digestAlgorithm.Length < 8) || (digestAlgorithm.Length > 9))
            {
                log.log(20, "ssh-rsa signature: (digestAlgorithm.length < 8) || (digestAlgorithm.length > 9)");
                return false;
            }

            byte[] digestAlgorithm_sha1 = new byte[] { (byte)(0x06), (byte)(0x05), (byte)(0x2b), (byte)(0x0e), (byte)(0x03), (byte)(0x02), (byte)(0x1a), (byte)(0x05), (byte)(0x00) };

            for (int i = 0; i < digestAlgorithm.Length; i++)
            {
                if (digestAlgorithm[i] != digestAlgorithm_sha1[i])
                {
                    log.log(20, "ssh-rsa signature: digestAlgorithm[i] != digestAlgorithm_sha1[i]");
                    return false;
                }
            }

            byte[] digest = dr.readOctetString();

            if (dr.available() != 0)
            {
                log.log(20, "ssh-rsa signature: dr.available() != 0 (II)");
                return false;
            }

            if (digest.Length != sha_message.Length)
            {
                log.log(20, "ssh-rsa signature: digest.length != sha_message.length");
                return false;
            }

            for (int i = 0; i < sha_message.Length; i++)
            {
                if (sha_message[i] != digest[i])
                {
                    log.log(20, "ssh-rsa signature: sha_message[i] != digest[i]");
                    return false;
                }
            }

            return true;
        }
        static RSASHA1Verify()
        {
            log = Logger.getLogger(typeof(RSASHA1Verify));
        }
    }
}